#!/usr/bin/ruby

require 'rubygems'
require 'mechanize'
require 'htmlentities'
#require 'tmpdir'

class Kowala
  class Browser
    def initialize ( url = "http://mail.emea.microsoftonline.com" )
      @agent = Mechanize.new
      @agent.user_agent_alias = "Mac Safari"
      @url = url
      @coder = HTMLEntities.new
    end

    def login(username, password)
      doc = @agent.get(@url)
      inlog_form = doc.forms.first
      @username = username
      inlog_form.username = username
      inlog_form.password = password
      @page = @agent.submit(inlog_form)
    end

    def unread
      list = []
      (@page/"tr[@style=\"font-weight:bold;\"]").each do |tr|
        id = CGI::escape((tr/"input[@type=\"checkbox\"]").first.attributes["value"].to_s)
        list << getMail(id)
      end
      return list
    end
    
    def parseRecipientList(list)
      parsedList = ""
      list.each do |t|
        parsedList += ", " unless parsedList == ""
        if(t/"a").count > 0 then
          parsedList += getAddress((t/"a").first.attributes["id"].to_s, t.inner_html.gsub(/<\/?[^>]*>/, "").strip)
        else
          parsedList += t.inner_html.gsub(/<\/?[^>]*>/, "").strip
        end
      end
      return parsedList
    end

    def getMail(id)
      m = {:id => id}
      m[:url] = "https://red002.mail.emea.microsoftonline.com/owa/?ae=Item&t=IPM.Note&id=" + m[:id]

      page = @agent.get(m[:url])

      m[:from] = (page/"td[@class=\"frm\"]/span").inner_html.gsub(/<\/?[^>]*>/, "").strip
      if (page/"td[@class=\"frm\"]/span/a").count > 0 then
        m[:from] = getAddress((page/"td[@class=\"frm\"]/span/a").first.attributes["id"].to_s, m[:from]) 
      else
        m[:from] = parseAddress(m[:from])
      end

      m[:to] = parseRecipientList((page/"div[@id=\"divTo\"]/span"))
      m[:cc] = parseRecipientList((page/"div[@id=\"divCc\"]/span"))
      
      m[:subject] = (page/"td[@class=\"sub\"]").inner_html.strip
      m[:body] = (page/"div[@class=\"bdy\"]").first.inner_html.gsub(/<\/?[^>]*>/, "")

      (page/"td[@class=\"hdtxt\"]").each do |veld|
         if veld.inner_html.strip == "Verzonden:" then
           m[:date] = veld.next_element.inner_html.strip
         end
      end

      m[:source] = ""
      m[:source] += "From: " + m[:from] + "\n"
      m[:source] += "Subject: " + m[:subject] + "\n"
      m[:source] += "To: #{m[:to]}\n"
      m[:source] += "Date: #{m[:date]}\n" 
      m[:source] += "\n"
      m[:source] += m[:body]
      m[:source] = @coder.decode(m[:source])
      return m
    end

    def getAddress(id, name)
      id = CGI::escape(id)
      url = "https://red002.mail.emea.microsoftonline.com/owa/?ae=Item&t=AD.RecipientType.User&id=" + id
      page = @agent.get(url)
      email = false
      (page/"td").each do |veld|
        if veld.inner_html.strip == "E-mail" then
          email = veld.next_sibling.inner_html.to_s
        end
      end
      return "\"#{name}\" <#{email}>"
    end
    
    def parseAddress(raw)
      if raw =~ /(.*) \[(.*)\]/
        return "\"#{$1}\" <#{$2}>"
      else
        return raw
      end
    end
    
  end
end


